﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Pixeldyne.Core.Data
{
	public class CsvReader
	{
		/// <summary>
		/// Reads a CSV file into a multi-dimensional array.
		/// </summary>
		/// <param name="path">The file path.</param>
		public static string[][] ReadCsvFile(string path)
		{
			if (string.IsNullOrWhiteSpace(path))
				throw new ArgumentNullException("path");

			if (!File.Exists(path))
				throw new FileNotFoundException("path", path);

			var rows = new List<string[]>();

			var sr = new StreamReader(path);

			int columnCount = 0;
			string line;

			while ((line = sr.ReadLine()) != null)
			{
				if (line.IndexOf("#", StringComparison.Ordinal) == 0)
					continue;

				string[] columns = line.Split(new[] { ',' });

				if (columns.Length == 0)
					continue;

				if (columnCount == 0)
					columnCount = columns.Length;

				if (columnCount != columns.Length)
					continue;

				for (int i = 0; i < columns.Length; i++)
				{
					if (string.IsNullOrEmpty(columns[i]))
						continue;

					if (columns[i].IndexOf('"') == 0)
					{
						columns[i] = columns[i].Trim('"');
					}
				}

				rows.Add(columns);
			}

			sr.Close();

			return rows.ToArray();
		}
	}
}
